#!/bin/sh

################################################################################
# Copyright 1999-2010 by Nice, srl.,
# Via Marchesi di Roero, 1
# 14020 Cortanze (AT) - ITALY
# All rights reserved.
#
# This software is the confidential and proprietary information
# of Nice, srl. ("Confidential Information").
# You shall not disclose such Confidential Information
# and shall use it only in accordance with the terms of
# the license agreement you entered into with Nice.
################################################################################

#------------------------------------------------------------------
# Create a new directory
#
# Usage: fm.new.folder <path> <old_name> <name>
#
# - path:  the current path (relative to vroot)
# - name:  the name of the directory to create
#
#------------------------------------------------------------------

. "${EF_ROOT}/plugins/irods/bin/common"
. "${EF_ROOT}/plugins/fm/fm/backends/common"

if [ -z "$1" ]; then
  fatal "Cannot create directory" "Missing input parameter: current path"
fi

if [ -z "$2" ]; then
  fatal "Cannot create directory" "Missing input parameter: name of directory to create"
fi

printf "$2" | grep "/" >/dev/null 2>&1
if [ $? -eq 0 ]; then
  error "Cannot create directory \"$2\"" "Slashes are not allowed in  directory names. Please use a different name."
fi

_fullpath="${1}/${2}"

# Change to the required directory
${IRODS_ICOMMANDS_DIR}/icd "${1}" >/dev/null 2>&1
if [ $? -ne 0 ]; then
    fatal "Cannot create directory \"$2\"" "Cannot access to working directory"
fi
#if [ -e "$2" ]; then
#    error "Cannot create directory \"$2\"" "The name \"$2\" is already used in this directory. Please use a different name."
#fi

_message="`${IRODS_ICOMMANDS_DIR}/imkdir \"${_fullpath}\" 2>&1`"
if [ $? -ne 0 ]; then
  # FIXME: it would be nice to report the actual error message to users in a portable way
  _message="`echo \"${_message}\" | cut -d: -f3`"
  error "Cannot create directory \"$2\"" "`trim ${_message}`"
fi


